<template>
  <div class="loginPage">
    <div class="l-main">
      <div class="system-info">
        <div class="system-logo">
          <img class="img-logo" :src="state.appLogo" alt="logo" />
        </div>
        <div class="system-name" v-html="state.appName"></div>
      </div>
      <div class="l-m-from">
        <div class="right-info">
          <div class="r-row">
            <div class="r-row-side">
              <span>用户名</span>
            </div>
            <div class="r-row-main">
              <a-input
                v-model:value="state.name"
                allow-clear
                size="large"
                placeholder="请输入用户名..."
                @keyup.enter="login"
              />
            </div>
          </div>
          <div class="r-row">
            <div class="r-row-side">
              <span>密码</span>
            </div>
            <div class="r-row-main">
              <a-input-password
                v-model:value="state.password"
                allow-clear
                size="large"
                placeholder="请输入密码..."
                @keyup.enter="login"
              />
            </div>
          </div>
          <div class="r-row">
            <div class="r-row-side">
              <span>验证码</span>
            </div>
            <div class="r-row-main">
              <a-input
                v-model:value="state.verifyCode"
                allow-clear
                size="large"
                style="width: 38%"
                placeholder="验证码..."
                @keyup.enter="login"
              />
              <div class="verify-wrap">
                <img
                  class="verify-img"
                  :src="state.verifyImg"
                  alt="验证码"
                  @click="getVerifyImg"
                />
                <span
                  class="verify-refresh fa fa-refresh"
                  @click="getVerifyImg"
                ></span>
              </div>
            </div>
          </div>
          <div class="r-row">
            <p class="info-foot">
              <a-button
                class="login-btn"
                size="large"
                type="primary"
                @click="login"
              >
                登录
              </a-button>
            </p>
          </div>
        </div>
        <div class="system-img">
          <!-- <img class="img-bg" :src="getImageUrl('login-img.png')" /> -->
        </div>
        <div class="com-name">长城网科©</div>
      </div>
    </div>
  </div>
  <PasswordModal
    v-model:show="state.showPassword"
    :name="state.name"
    isLogin
    :token="state.token"
    @callback="logOut"
  />
  <SuVersion :text="state.version" />
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { md5 } from 'js-md5';
import { getAssetsFile } from 'commons/src/imgUtil';
import { getHrefTsp } from 'utils/src/urlLocalSet';
import PasswordModal from '../home/passwordModal.vue';
import SuVersion from 'components/src/su-version/index.vue';
import loginApi from 'apis/src/portal/login';
import { useRouter } from 'vue-router';
const router = useRouter();
const appCode = import.meta.env.VITE_BASE_PORTAL_CODE;
// 作为登录的唯一标识ID，以便于校验验证码
const loginId = Date.now().toString() + Math.random() * 1000;

const state = reactive({
  appLogo: '', // 项目logo
  appName: '', // 项目名称
  version: '', // 项目版本号
  name: '',
  password: '',
  verifyCode: '',
  verifyImg: '',
  token: '',
  showPassword: false, // 修改密码模态框
});
onMounted(() => {
  verifyLogin();
  getAppInfo();
  getVerifyImg();
});

// 验证登录
const verifyLogin =  () => {
  const token = localStorage.getItem('token');
  const isPwdExpired = localStorage.getItem('isPwdExpired');
  // 密码不过期才进行校验
  if (token && isPwdExpired === 'N') {
    const href = getHrefTsp();
    loginApi.verifyLogin(token).then((res) => {
      if (res.data === true) {
        //token在有效期 且tsp为合法移动端 无需登录
        if (href && href.includes('staticH5')) {
          window.location.href =
            href + (href.includes('?') ? '&' : '?') + `token=${token}`;
        } else if (token) {
          //当前portal项目
          router.push('/home');
        }
      } else {
        localStorage.removeItem('token');
        localStorage.removeItem('isPwdExpired');
        localStorage.removeItem('encryp');
      }
    });
  }
};
// 获取系统信息
const getAppInfo = () => {
  loginApi.getPortalInfo().then((res) => {
    state.appLogo = res.data.logUrl || getAssetsFile('app-logo.svg');
    state.appName = res.data.name || '医疗质量监控管理平台';
    state.version = res.data.version || 'v1.0.1';
  });
};
// 获取验证码图片
const getVerifyImg = () => {
  loginApi.getVerifyImg(loginId).then((res) => {
    state.verifyImg = res.data.img || '';
    // 临时使用（便于配合测试安全检查）
    // state.verifyCode = res.data.verifyCode
  });
};

// 登录
const login = () => {
  const { name, password, verifyCode } = state;
  if (!name) return message.warning('用户名不能为空！');
  if (!password) return message.warning('密码不能为空！');
  // if (!verifyCode) return message.warning('验证码不能为空！')

  const params = {
    code: name,
    password: md5(md5(password)),
    loginId,
    verifyCode,
    appCode,
  };
  loginApi.getLogin(params).then(
    (res) => {
      const { token, isPwdExpired } = res.data;
      // 密码过期
      state.token = token;
      localStorage.setItem('token', token);
      localStorage.setItem('isPwdExpired', isPwdExpired);
      if (isPwdExpired === 'Y') {
        state.showPassword = true;
      } else {
        const href = getHrefTsp();
        if (href && href.includes('staticH5')) {
          // // 如果是移动端查检，返回home页
          // if (href.includes('/mobileCheck/staticH5/')) {
          window.location.href =
            href + (href.includes('?') ? '&' : '?') + `token=${token}`;
          // window.location.href = getHref().tsp.split('#')[0] + '#/pages/business/home' + `?token=${token}`
          // } else {
          //   window.location.href = getHrefTsp() + `?token=${token}`
          // }
        } else {
          router.push('/home');
        }
      }
    },
    (err) => {
      console.log(err);
      localStorage.removeItem('token');
      localStorage.removeItem('isPwdExpired');
      getVerifyImg();
    }
  );
};
// ajax退出登录
const logOut = () => {
  loginApi.logOut().then(() => {
    localStorage.removeItem('token');
    localStorage.removeItem('isPwdExpired');
    location.reload();
  });
};
</script>

<style lang="scss" scoped>
@import 'commons/src/css/scss/variate.scss';
.com-name {
  position: absolute;
  bottom: -30px;
  right: 3px;
  font-size: 12px;
  color: #979ba0;
}
.loginPage {
  width: 100%;
  height: 100%;
  padding: 2% 5%;
  background: #f1f3f2 url('../../assets/imgs/login-bg.png') no-repeat;
  background-size: cover;
  overflow: auto;
}
.l-main {
  width: 100%;
  height: 100%;

  .system-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    position: fixed;
    top: 7%;
    left: 5%;
    right: 5%;

    .system-logo {
      width: 184px;
      height: 44px;
      display: flex;
      justify-content: flex-start;
      overflow: hidden;
      .img-logo {
        width: 100%;
      }
    }

    .system-name {
      padding-top: 10px;
      color: $theme-text-color;
      font-size: 28px;
      letter-spacing: 3px;
      text-align: center;
    }
  }

  .system-img {
    width: 100vm;
    position: absolute;
    bottom: 0;
    .img-bg {
      width: 100%;
    }
  }

  .l-m-from {
    padding: 6%;
    display: flex;
    height: 60%;
    min-height: 480px;
    justify-content: center;
    align-items: center;
    border-radius: 20px;
    border: 1px solid #fff;
    background-color: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(5px) saturate(160%);
    -webkit-backdrop-filter: blur(5px) saturate(160%);
    position: fixed;
    top: 25%;
    left: 5%;
    right: 5%;

    .right-info {
      width: 1005;
      position: relative;
      z-index: 1;
      backdrop-filter: blur(5px) saturate(160%);
      -webkit-backdrop-filter: blur(5px) saturate(160%);

      .r-row {
        padding-bottom: 28px;
      }

      .r-row-side {
        color: #5a6a81;
        font-size: 14px;
        padding-left: 10px;
      }

      .r-row-side + .r-row-main {
        padding-top: 10px;
        display: flex;
        align-items: center;
      }

      .info-title {
        text-align: center;
        font-size: 22px;
        line-height: 30px;
        color: #5a6a81;
      }

      .ant-input-affix-wrapper-lg {
        height: 48px;
        padding: 10px 18px;
        background-color: #fff;
        box-shadow: 18px 20px 32px 0px rgba(184, 200, 224, 0.22);
        border: solid 1px rgba(255, 255, 255, 0.18);
        border-radius: 16px;
        font-size: 14px;
      }

      .verify-wrap {
        display: inline-flex;
        align-items: center;
        position: relative;

        &::after {
          display: none;
          content: '点击刷新';
          color: $blue-color;
          font-size: 13px;
          position: absolute;
          left: 12px;
          bottom: -25px;
        }

        &:hover {
          &::after {
            display: block;
          }
        }

        .verify-img {
          margin-left: 5px;
          width: 65%;
          min-width: 150px;
          height: 48px;
          background-color: #fff;
          border-radius: 16px;
          cursor: pointer;
        }

        .verify-refresh {
          color: #7d8592;
          font-size: 18px;
          cursor: pointer;

          &:hover {
            color: $blue-color;
          }
        }
      }

      .info-foot {
        display: flex;
        justify-content: center;
        padding-top: 2vh;

        .login-btn {
          width: 110px;
          height: 40px;
          box-shadow: 0px 6px 12px 0px rgba(63, 140, 255, 0.26);
          border-radius: 14px;
        }
      }
    }
  }
}
</style>
